package cc.deng.wubo.minapp.controller;

import cc.deng.wubo.minapp.beans.SysMenu;
import cc.deng.wubo.minapp.beans.SysRole;
import cc.deng.wubo.minapp.beans.SysUser;
import cc.deng.wubo.minapp.service.MenuService;
import cc.deng.wubo.minapp.service.RoleService;
import cc.deng.wubo.minapp.service.UserService;
import cc.deng.wubo.minapp.utils.StringUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    private final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;




    @ResponseBody
    @PostMapping("/loadMenuInfo")
    public String loadMenuInfo(HttpSession session,Integer parentId)throws Exception{
        SysRole currentRole = (SysRole)session.getAttribute("currentRole");
        return getAllMenuByParentId(parentId,currentRole.getId()).toString();
    }

    /**
     * 获取所有菜单信息
     * @param parentId
     * @param roleId
     * @return
     */
    public JsonArray getAllMenuByParentId(Integer parentId,Integer roleId){
        JsonArray jsonArray = this.getMenuByParentId(parentId,roleId);
        for(int i=0;i<jsonArray.size();i++){
            JsonObject jsonObject = (JsonObject) jsonArray.get(i);
            if ("open".equals(jsonObject.get("state").getAsString())){
                continue;
            }else{
                jsonObject.add("children",getAllMenuByParentId(jsonObject.get("id").getAsInt(),roleId));
            }

        }
        return jsonArray;
    }
    /**
     * 根据父节点和用户角色ID查询菜单
     * @param parentId
     * @param roleId
     * @return
     */
    public JsonArray getMenuByParentId(Integer parentId,Integer roleId){
        List<SysMenu> menuList = menuService.findByParentIdAndRoleId(parentId, roleId);
        JsonArray jsonArray = new JsonArray();
        for (SysMenu menu:menuList){
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id",menu.getId());
            jsonObject.addProperty("text",menu.getName());

            if (menu.getState()==1){
                jsonObject.addProperty("state","closed"); // 根节点
            }else{
                jsonObject.addProperty("state","open"); // 叶子节点
            }
            jsonObject.addProperty("iconCls",menu.getIcon());   // 节点图标
            JsonObject attributeObject = new JsonObject();  //扩展属性
            attributeObject.addProperty("url",menu.getUrl()); // 菜单请求地址
            jsonObject.add("attributes",attributeObject);
            jsonArray.add(jsonObject);

        }

        return jsonArray;
    }


    @ResponseBody
    @GetMapping("/loadUserInfo")
    public String loadUserInfo(HttpSession session)throws Exception{
        SysUser currentUser = (SysUser) session.getAttribute("currentUser");
        return "欢迎您"+currentUser.getTrueName();
    }


    @ResponseBody
    @RequestMapping("/login")
    public Object login (String userName, String password, HttpSession session){
        NutMap result = new NutMap();


        if (StringUtil.isEmpty(userName)){
            result.put("success",false);
            result.put("errorInfo","用户名不能为空!");
            return  result;
        }
        if (StringUtil.isEmpty(password)){
            result.put("success",false);
            result.put("errorInfo","密码不能为空!");
            return  result;
        }

        SysUser user = userService.fetch(Cnd.where("userName","=",userName));
        List<SysRole> roleList = roleService.findByUserId(user.getId());

        Subject subject = SecurityUtils.getSubject();
        String slat = user.getSlat();
        password =  new Sha256Hash(password,slat).toHex();
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);

        try{
            subject.login(token);
            session.setAttribute("currentUser",user);
            session.setAttribute("uid",user.getId());
            session.setAttribute("currentRole",roleList.get(0));
            result.put("success",true);

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            result.put("success",false);
            result.put("errorInfo","用户名或密码错误!");
        }
        return result;
    }


}
